/*
 * author: Andriamananony, Meß, Falk
 */

package auftrag;

import java.util.ArrayList;
import java.util.Collections;

import util.Interval;

public class Ressource {
	private String strRessourceName;
	private ArrayList<Interval> mIntervals = new ArrayList<Interval>();
	private int maxTime = 0;

	public Ressource(String strRessourceName) {
		this.strRessourceName = strRessourceName;
	}

	@Override
	public String toString() {
		return this.strRessourceName;
	}
	
	public void clear(){
		mIntervals.clear();
		maxTime = 0;
	}
	
	public int getMaxTime(){
		return maxTime;
	}
	
	public boolean addInterval(Interval pI){
		maxTime = Math.max(maxTime, pI.getEnd());
		for(int i = 0; i<mIntervals.size();i++){
			if(mIntervals.get(i).compareTo(pI) == 1){
				mIntervals.add(i, pI);
				return true;
			}
		}
		mIntervals.add(pI);
		return true;
	}
	
	public Interval getFirstUnoccupiedInterval(int start, int d){
		int nIndexOfLast = 0;
		Interval tmpCompare = new Interval(start,start+d);
		for(Interval i : mIntervals.subList(nIndexOfLast, mIntervals.size())){
			if(i.overlapsWith(tmpCompare)){
				tmpCompare.moveTo(i.getEnd());
			} else if(i.compareTo(tmpCompare) == 1)
				break;
		}
		
		return tmpCompare;
		
	}
	
	public double getAuslastung(int maxTime){
		if(getMaxTime() <= 0)
			return 0;
		double time = 0;
		Collections.sort(mIntervals);
		for(Interval i : mIntervals)
			time += i.getDuration();
		return time / maxTime;
	}
}
